package avicit.bdp.dgs.metadata.service;

import avicit.bdp.common.base.BaseService;
import avicit.bdp.common.service.dto.BdpColumnDTO;
import avicit.bdp.common.service.dto.BdpTableDTO;
import avicit.bdp.common.utils.CheckParaUtils;
import avicit.bdp.common.utils.EntityUtils;
import avicit.bdp.dgs.metadata.dao.MetadataColumnTmpDao;
import avicit.bdp.dgs.metadata.dto.MetadataColumnTmpDTO;
import avicit.bdp.dgs.metadata.dto.MetadataTmpDTO;
import avicit.bdp.dgs.metadata.vo.MetadataColumnEditVo;
import avicit.platform6.commons.utils.ComUtil;
import avicit.platform6.core.exception.DaoException;
import avicit.platform6.core.rest.msg.QueryRespBean;
import avicit.platform6.modules.system.syslog.service.SysLogUtil;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import java.util.ArrayList;
import java.util.List;
import javax.annotation.Resource;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

@Service
public class MetadataColumnTmpService
    extends BaseService<MetadataColumnTmpDao, MetadataColumnTmpDTO> {

  private static final Logger LOGGER = LoggerFactory.getLogger(MetadataColumnTmpService.class);

  @Resource private MetadataTmpService metadataTmpService;
  @Resource private MetadataTableColumnService metadataTableColumnService;
  @Resource private MetadataTableService metadataTableService;

  /**
   * 按条件分页查询
   *
   * @param metadataId 暂存元数据ID
   * @param keyWords 关键词
   */
  @Transactional(readOnly = true)
  public QueryRespBean<MetadataColumnTmpDTO> getPageList(
      String metadataId, String keyWords, Integer pageNo, Integer pageSize) {
    QueryRespBean<MetadataColumnTmpDTO> queryRespBean = new QueryRespBean<>();

    // 先查询是否有编辑过，如果没有，返回元数据历史记录中的最新版本的列数据
    // 如果有过编辑，直接返回暂存区的列数据
    MetadataTmpDTO metadataTmpDTO = metadataTmpService.queryByMetadataId(metadataId);
    if (metadataTmpDTO != null) {
      PageHelper.startPage(pageNo, pageSize);
      Page<MetadataColumnTmpDTO> dataList = this.mapper.getPageList(metadataId, keyWords);
      queryRespBean.setResult(dataList);
    } else {
      Page<BdpColumnDTO> page =
          metadataTableColumnService.selectPageList(metadataId, keyWords, pageNo, pageSize);
      List<MetadataColumnTmpDTO> voList = new ArrayList<>();
      List<BdpColumnDTO> columnDTOS = page.getResult();
      for (BdpColumnDTO columnDTO : columnDTOS) {
        MetadataColumnTmpDTO columnTmpDTO = new MetadataColumnTmpDTO();
        BeanUtils.copyProperties(columnDTO, columnTmpDTO);
        columnTmpDTO.setMetadataId(metadataId);
        voList.add(columnTmpDTO);
      }

      Page<MetadataColumnTmpDTO> pageResult = new Page<>(pageNo, pageSize);
      pageResult.setTotal(page.getTotal());
      pageResult.addAll(voList);
      queryRespBean.setResult(pageResult);
    }

    return queryRespBean;
  }

  /**
   * 批量更新或新增对象
   *
   * @param metadataColumnEditVo 修改对象
   * @return int
   */
  @Transactional
  public int batchSaveOrUpdate(MetadataColumnEditVo metadataColumnEditVo) {

    String metadataId = metadataColumnEditVo.getMetadataId();
    String metadataVersion = metadataColumnEditVo.getMetadataVersion();
    List<MetadataColumnTmpDTO> columnList = metadataColumnEditVo.getMetadataColumnDTOList();

    CheckParaUtils.checkStringValidity(metadataId, LOGGER, "元数据ID不能为空");
    CheckParaUtils.checkStringValidity(metadataVersion, LOGGER, "元数据版本不能为空");
    CheckParaUtils.checkCollectionValidity(columnList, LOGGER, "没有变更的数据");

    // 表元数据结构有变更，记录变更记录
    MetadataTmpDTO metadataTmpDTO = metadataTmpService.queryByMetadataId(metadataId);
    if (metadataTmpDTO == null) {
      metadataTmpDTO = new MetadataTmpDTO();
      BdpTableDTO bdpTableDTO = metadataTableService.selectByPrimaryKey(metadataId);
      CheckParaUtils.checkObjectValidity(bdpTableDTO, LOGGER, "元数据不存在");

      BeanUtils.copyProperties(bdpTableDTO, metadataTmpDTO);

      metadataTmpDTO.setId(ComUtil.getId());
      metadataTmpDTO.setMetadataId(metadataId);
      metadataTmpDTO.setMetadataVersion(metadataVersion);
      metadataTmpService.save(metadataTmpDTO);
    }

    // 将新版本的列数据添加到暂存区
    int existNum = this.mapper.countByMetadataId(metadataId);
    if (existNum == 0) {
      BdpColumnDTO queryColumn = new BdpColumnDTO();
      queryColumn.setTableId(metadataId);
      List<BdpColumnDTO> latestColumnList = metadataTableColumnService.selectList(queryColumn);
      if (CollectionUtils.isNotEmpty(latestColumnList)) {
        List<MetadataColumnTmpDTO> addList = new ArrayList<>();
        for (BdpColumnDTO columnDTO : latestColumnList) {
          MetadataColumnTmpDTO columnTmpDTO = new MetadataColumnTmpDTO();
          BeanUtils.copyProperties(columnDTO, columnTmpDTO);
          columnTmpDTO.setMetadataId(metadataId);
          addList.add(columnTmpDTO);
        }
        this.mapper.batchSave(addList);
      }
    }

    List<MetadataColumnTmpDTO> addList = new ArrayList<>();
    List<MetadataColumnTmpDTO> updateList = new ArrayList<>();

    Integer maxOrder = this.mapper.selectMaxOrderByMetadataId(metadataId);

    for (MetadataColumnTmpDTO columnTmpDTO : columnList) {
      columnTmpDTO.setMetadataId(metadataId);
      if (StringUtils.isEmpty(columnTmpDTO.getId())) {
        maxOrder = maxOrder == null ? 0 : maxOrder + 1;
        columnTmpDTO.setId(ComUtil.getId());
        columnTmpDTO.setOrderBy(maxOrder);
        EntityUtils.setCreateAndUpdateInfo(columnTmpDTO);
        addList.add(columnTmpDTO);
      } else {
        EntityUtils.setUpdatedInfo(columnTmpDTO);
        updateList.add(columnTmpDTO);
      }
    }

    int result = 0;
    if (CollectionUtils.isNotEmpty(addList)) {
      result += this.mapper.batchSave(addList);
    }

    if (CollectionUtils.isNotEmpty(updateList)) {
      result += this.mapper.batchUpdate(updateList);
    }

    return result;
  }

  /**
   * 按主键单条删除
   *
   * @param id 主键id
   * @return int
   */
  @Transactional
  public int deleteById(String id) {
    if (StringUtils.isEmpty(id)) {
      throw new DaoException("删除失败！传入的参数主键为空");
    }
    try {
      // 记录日志
      MetadataColumnTmpDTO bdpDgsColumnTmpDTO = this.mapper.selectByPrimaryKey(id);
      if (bdpDgsColumnTmpDTO == null) {
        throw new DaoException("删除失败！对象不存在");
      }
      SysLogUtil.log4Delete(bdpDgsColumnTmpDTO);
      return this.mapper.deleteByPrimaryKey(id);
    } catch (Exception e) {
      throw new DaoException(e.getMessage(), e);
    }
  }

  public void deleteByMetadataId(String metadataId) {
    if (StringUtils.isEmpty(metadataId)) {
      throw new DaoException("删除失败！传入的参数主键为空");
    }

    MetadataColumnTmpDTO metadataColumnTmpDTO = new MetadataColumnTmpDTO();
    metadataColumnTmpDTO.setMetadataId(metadataId);
    this.mapper.delete(metadataColumnTmpDTO);
  }

  public void batchSave(List<MetadataColumnTmpDTO> metadataColumnTmpDTOList) {
    this.mapper.batchSave(metadataColumnTmpDTOList);
  }
}
